<?php

namespace Xrfg\Wallet\USDT\Services;

use App\Models\User;
use App\Models\Withdraw;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

/**
 * @method omni_funded_send(string $fromAddress, string $toAddress, int $id, string $number, string $feeAddress)
 */
class USDTWallet
{
    /**
     * @var \GuzzleHttp\Client
     */
    public $http;

    /**
     * ETHService constructor.
     */
    public function __construct()
    {
        $this->http = new Client();
    }

    /**
     * @param User $user
     *
     * @return mixed
     *
     * @throws Exception
     */
    public function newAccount(User $user)
    {
        return self::request('getnewaddress', [(string) $user->id]);
    }

    /**
     * @param array $params
     *
     * @return mixed
     *
     * @throws Exception
     */
    public function listTransactions($params = [])
    {
        return self::request('omni_listtransactions', $params);
    }

    public function transfer(Withdraw $withdraw)
    {
        $from = config('wallet.usdt.withdraw_address');
        $to = $withdraw->address;
        $id = 31;
        $number = $withdraw->number();

        try {
            $hash = $this->omni_funded_send($from, $to, $id, (string) $number, $from);
            $withdraw->hash = $hash;
            $withdraw->status = Withdraw::STATUS_SUCCESS;
            $withdraw->save();
        } catch (Exception $exception) {
            Log::error($exception);
        }
    }

    /**
     * @param string $method
     * @param array  $params
     *
     * @return mixed
     *
     * @throws Exception
     */
    protected function request($method, $params = [])
    {
        $response = $this->http->post(config('wallet.usdt.rpc.url'), [
            'timeout' => config('wallet.usdt.rpc.timeout'),
            'auth' => config('wallet.usdt.rpc.auth'),
            'json' => [
                'id' => time(),
                'jsonrpc' => '1.0',
                'method' => $method,
                'params' => $params,
            ],
        ]);

        $content = json_decode($response->getBody()->getContents(), true);
        if (null !== $content['error']) {
            Log::error(json_encode($content['error']));
            throw new Exception('RPC ERROR');
        }

        return $content['result'];
    }

    /**
     * @param $name
     * @param $arguments
     *
     * @return \Psr\Http\Message\ResponseInterface
     *
     * @throws Exception
     */
    public function __call($name, $arguments)
    {
        return self::request($name, $arguments);
    }
}
